package com.shensi.adminCollect.controller.station;


import com.alibaba.fastjson.JSONObject;
import com.shensi.adminCollect.common.constant.UserConstants;
import com.shensi.common.core.controller.BaseController;
import com.shensi.common.core.domain.AjaxResult;
import com.shensi.common.core.domain.ResultData;
import com.shensi.common.core.page.TableDataInfo;
import com.shensi.adminCollect.common.exception.BaseException;
import com.shensi.adminCollect.common.utils.StringUtils;
import com.shensi.adminCollect.common.utils.poi.ExcelUtil;
import com.shensi.adminCollect.domain.station.dto.PhysicalCardBalanceDto;
import com.shensi.adminCollect.domain.station.dto.PhysicalCardBalanceListDto;
import com.shensi.adminCollect.domain.station.dto.PhysicalCardSecretKeyDto;
import com.shensi.adminCollect.service.station.IPhysicalCardBalanceService;
import com.shensi.adminCollect.service.station.IPhysicalCardService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

import com.shensi.common.core.domain.model.LoginUser;
import com.shensi.common.core.utils.SecurityUtils;
import com.shensi.common.core.domain.entity.SysUser;
/**实体卡充值/消费记录信息*/

@RestController
@RequestMapping("/physicalCardBalance")
@Slf4j
@Api(value = "实体卡充值/消费记录信息接口",description = "实体卡充值/消费记录信息接口")
public class PhysicalCardBalanceController extends BaseController{

    @Autowired
    private IPhysicalCardBalanceService physicalCardBalanceService;

    @Autowired
    private IPhysicalCardService physicalCardService;

    @Value("${physicalCard.secretKeyA}")
    private String SECRET_KEY_A;

    @Value("${physicalCard.secretKeyB}")
    private String SECRET_KEY_B;
    @Value("${qujia.payBaseUrl}")
    private String payBaseUrl;
    /**实体卡充值*/
    @PostMapping("/recharge")
    @ApiOperation(value = "实体卡充值",response = PhysicalCardSecretKeyDto.class)
    @Transactional
    public AjaxResult recharge(@RequestBody PhysicalCardBalanceDto physicalCardBalanceDto){
        return AjaxResult.error("后台充值停止使用，请到指定渠道充值");

//        if(Objects.isNull(physicalCardBalanceDto) || StringUtils.isEmpty(physicalCardBalanceDto.getPhysicalCardNo())){
//            return AjaxResult.error("请求参数异常");
//        }
//        physicalCardBalanceDto.setPhysicalCardNo(StringUtils.trim(physicalCardBalanceDto.getPhysicalCardNo()));
//        log.info("实体卡充值 请求参数：[{}]",JSONObject.toJSONString(physicalCardBalanceDto));
//        PhysicalCardBalance physicalCardBalance = new PhysicalCardBalance();
//        BeanUtils.copyProperties(physicalCardBalanceDto,physicalCardBalance);
//        log.info("PhysicalCardBalanceController.recharge请求参数：[{}]",JSONObject.toJSONString(physicalCardBalance));
//        if(Objects.isNull(physicalCardBalance.getAmount())){
//            return AjaxResult.error("请输入充值金额");
//        }
//        PhysicalCard physicalCard = physicalCardService.selectPhysicalCard(physicalCardBalance.getPhysicalCardNo());
//        if(Objects.isNull(physicalCard)){
//            return AjaxResult.error("实体卡不存在");
//        }
//        if(StringUtils.isEmpty(physicalCard.getStationId()) || StringUtils.isEmpty(physicalCardBalanceDto.getCurrStationId())){
//            return AjaxResult.error("油站不存在");
//        }
//        checkStationId(physicalCard.getStationId(),physicalCardBalanceDto.getCurrStationId());
//        if(physicalCardService.physicalCardType(physicalCard)){
//            return AjaxResult.error("定额卡不允许充值");
//        }
//        SysUser user = SecurityUtils.getLoginUser().getUser();
//        // 修改实体卡面额
//        if(Objects.isNull(physicalCard.getPhysicalCardAmount())
//                || (physicalCard.getPhysicalCardAmount().signum() == 0)){
//            physicalCard.setPhysicalCardAmount(physicalCardBalance.getAmount());
//            physicalCard.setUpdateBy(user.getUserName());
//            physicalCardService.updatePhysicalCard(physicalCard);
//            physicalCardBalance.setBalanceAmount(physicalCardBalance.getAmount());
//        } else {
//            BigDecimal amount = physicalCard.getPhysicalCardAmount().add(physicalCardBalance.getAmount());
//            physicalCard.setPhysicalCardAmount(amount);
//            physicalCard.setUpdateBy(user.getUserName());
//            physicalCardService.updatePhysicalCard(physicalCard);
//            physicalCardBalance.setBalanceAmount(amount);
//        }
//
//        //增加充值记录
//        physicalCardBalance.setBalanceType(BalanceTypeEnum.RECHARGE.getValue());
//        physicalCardBalance.setEnterpriseId(physicalCard.getEnterpriseId());
//        physicalCardBalance.setEnterpriseName(physicalCard.getEnterpriseName());
//        physicalCardBalance.setStationId(physicalCardBalanceDto.getCurrStationId());
//        physicalCardBalance.setPayment(PhysicalCardPaymentEnum.MANUAL_ADD.getValue());
//        physicalCardBalanceService.addPhysicalCardBalance(physicalCardBalance);
//            String url = payBaseUrl+"/reductionActivity/createActivityBalanceRecord";
//            ReductionActivityBalanceRecord record=new ReductionActivityBalanceRecord();
//            record.setRechargeAmt(physicalCardBalance.getAmount());
//            record.setPhysicalCardNo(physicalCardBalance.getPhysicalCardNo());
//            record.setPaymentMethod("xj");
//            record.setEnterpriseId(physicalCard.getEnterpriseId());
//            if(StringUtils.isNotEmpty(physicalCardBalanceDto.getCurrStationId())){
//            record.setStationId(Long.parseLong(physicalCardBalanceDto.getCurrStationId()));
//        }
//
//            String resultJson = "";
//            try {
//                resultJson = HttpUtils.connectPostUrl(url, JSON.toJSONString(record));
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
//        log.info("立减活动返回信息：" + resultJson);
//        PhysicalCardSecretKeyDto physicalCardSecretKeyDto = new PhysicalCardSecretKeyDto();
//        physicalCardSecretKeyDto.setPhysicalCardNo(physicalCardBalanceDto.getPhysicalCardNo());
//        physicalCardSecretKeyDto.setSecretKeyA(SECRET_KEY_A);
//        physicalCardSecretKeyDto.setSecretKeyB(SECRET_KEY_B);
//
//        return AjaxResult.success(physicalCardSecretKeyDto);
    }

    private void checkStationId(String stationIds, String currStationId){
        if(StringUtils.isEmpty(stationIds) || StringUtils.isEmpty(currStationId)){
            throw new BaseException("实体卡充值--油站不存在");
        }
        List<String> list = Arrays.stream(stationIds.split(",")).collect(Collectors.toList());
        if(!list.contains(currStationId)){
            throw new BaseException("实体卡充值--油站不属于充值油站");
        }
    }

    /**查询充值/消费记录列表*/
    @GetMapping("/list")
    @ApiOperation(value = "查询充值/消费记录列表",response = PhysicalCardBalanceListDto.class)
    public TableDataInfo physicalCardBalanceList(PhysicalCardBalanceListDto physicalCardBalanceListDto){

        // 油企账号查询 只能看本油企
        Long enterpriseId = SecurityUtils.getLoginUser().getUser().getEnterpriseId();
        if(Objects.nonNull(enterpriseId)) {
            physicalCardBalanceListDto.setEnterpriseId(enterpriseId);
        }

        Long stationId = SecurityUtils.getLoginUser().getUser().getStationId();
        if(Objects.nonNull(stationId)){
            physicalCardBalanceListDto.setStationId(String.valueOf(stationId));
        }

        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        if(UserConstants.LEVEL_TWO.equals(sysUser.getUserLevel()) || UserConstants.LEVEL_THREE.equals(sysUser.getUserLevel())){
            physicalCardBalanceListDto.setIsDeleted("0");
        }


        startPage();
        physicalCardBalanceListDto.setStatus("1");
        List<PhysicalCardBalanceListDto> balanceList = physicalCardBalanceService.selectPhysicalCardBalanceList(physicalCardBalanceListDto);
        log.info("查询充值/消费记录列表PhysicalCardBalanceController.physicalCardBalanceList:[{}]", JSONObject.toJSONString(balanceList));
        return getDataTable(balanceList);
    }


    /**导出充值/消费记录Excel表*/
    @GetMapping("/export")
    @ApiOperation(value = "导出充值/消费记录Excel表",response = PhysicalCardBalanceListDto.class)
    public AjaxResult export(PhysicalCardBalanceListDto physicalCardBalanceListDto){
        // 油企账号查询 只能看本油企
        Long enterpriseId = SecurityUtils.getLoginUser().getUser().getEnterpriseId();
        if(Objects.nonNull(enterpriseId)) {
            physicalCardBalanceListDto.setEnterpriseId(enterpriseId);
        }

        Long stationId = SecurityUtils.getLoginUser().getUser().getStationId();
        if(Objects.nonNull(stationId)){
            physicalCardBalanceListDto.setStationId(String.valueOf(stationId));
        }

        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        if(UserConstants.LEVEL_TWO.equals(sysUser.getUserLevel()) || UserConstants.LEVEL_THREE.equals(sysUser.getUserLevel())){
            physicalCardBalanceListDto.setIsDeleted("0");
        }

        List<PhysicalCardBalanceListDto> balanceList = physicalCardBalanceService.selectPhysicalCardBalanceList(physicalCardBalanceListDto);
        log.info("EXCEL导出PhysicalCardBalanceController.physicalCardBalanceList:[{}]", JSONObject.toJSONString(balanceList));
        ExcelUtil<PhysicalCardBalanceListDto> util = new ExcelUtil<PhysicalCardBalanceListDto>(PhysicalCardBalanceListDto.class);
        return util.exportExcel(balanceList,"physicalCardBalance");
    }

    @GetMapping("refund")
    public ResultData<Long> refund(@RequestParam Long id){
        return ResultData.success(physicalCardBalanceService.posRechargeRefund(id));
    }

    /**实体卡订单列表统计*/
    @GetMapping("/statistics")
    @ApiOperation(value = "实体卡订单列表统计",response = PhysicalCardBalanceListDto.class)
    public AjaxResult physicalCardBalanceStatistics(PhysicalCardBalanceListDto physicalCardBalanceListDto){
        SysUser user = SecurityUtils.getLoginUser().getUser();

        if(UserConstants.LEVEL_TWO.equals(user.getUserLevel())){
            physicalCardBalanceListDto.setEnterpriseId(user.getEnterpriseId());
        }

        if(UserConstants.LEVEL_THREE.equals(user.getUserLevel())){
            physicalCardBalanceListDto.setStationId(String.valueOf(user.getStationId()));
        }
        physicalCardBalanceListDto.setStatus("1");
        PhysicalCardBalanceListDto physicalCardBalance = physicalCardBalanceService.selectPhysicalCardBalanceStatistics(physicalCardBalanceListDto);
        return AjaxResult.success(physicalCardBalance);
    }

}
